<?php
/**
 * Bee 范米粒采集器，像蜜蜂一样去采集数据
 */
namespace app\bee\controller;
use \DOMDocument;
use \DateTime;
use think\Controller;

define('UPLOAD_PATH', ROOT_PATH . "public/upload/goods/");

class BeeController extends Controller {
  public function request($url, $opt=null) {
    if (!isset($url)) {
      die('$url is required');
    }
    ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)'); 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    // curl_setopt($ch, CURLOPT_POSTFIELDS, 1);
    // curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
    curl_setopt($ch, CURLOPT_COOKIEFILE, '');
    curl_setopt($ch, CURLOPT_TIMEOUT,30);
    curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // var_dump($ch);
    // var_dump($response);
    if (is_array($opt) && !empty($opt)) {
      curl_setopt($ch,CURLOPT_HTTPHEADER,$opt['header']);
    }
    return curl_exec($ch);
  }
  
  public function downloadImage($imageURL) {
    $date_time = new DateTime();
    $image_path = self::UPLOAD_PATH . $date_time->format('Y/m-d') . '/';
    $fh = fopen($imageURL, 'r');
    $file_path = $image_path . $id . ".jpg";
    // 创建文件夹
    if (!is_dir($image_path)){
      mkdir($image_path, 0777, true);
    }
    if (!file_exists($file_path)) {
      file_put_contents($file_path, $fh);
    }
    $result = substr($file_path, strlen(ROOT_PATH));
    return $result;
  }
}